package com.tbs.easyhomemoneyserver.auths

import com.tbs.easyhomemoneyserver.DO.ApiLimit
import com.tbs.easyhomemoneyserver.constants.ApiRightsConstants
import com.tbs.easyhomemoneyserver.constants.BeanNameConstants
import com.tbs.easyhomemoneyserver.constants.HomeConstants
import com.tbs.easyhomemoneyserver.model.rights.ApiRequest
import com.tbs.easyhomemoneyserver.service.IApiLimitService
import com.tbs.easyhomemoneyserver.service.IHomeGroupService
import org.apache.dubbo.config.annotation.DubboReference
import org.apache.dubbo.config.annotation.DubboService
import java.util.*

/**
 * 家庭组权限验证，家长拥有完全权限，非家长需要拥有相关权限，非家庭组内验证失败
 * @author abstergo
 */
@DubboService(group = BeanNameConstants.PARENT_USER_AUTH)
class ParentUserAuth : SimpleContainsAuth() {
    @DubboReference(lazy = true)
    lateinit var homeGroupService: IHomeGroupService

    @DubboReference(lazy = true)
    lateinit var apiLimitService: IApiLimitService

    var customUnAuthText: String? = null;

    //    companion object {
    //        val log = LoggerFactory.getLogger(ParentUserAuth::class.java)
    //    }

    override fun auth(
        limit: ApiLimit, apiRequest: ApiRequest
    ): Boolean {
        val loginInfo = apiRequest.loginInfo
        if (!apiRequest.login || loginInfo == null) { //            log.warn("未登录的家庭权限验证")
            customUnAuthText = "未登录的家庭权限验证"
            return false
        }
        val loginUserId = loginInfo.userId
        if (loginUserId == null) { //            log.warn("登录信息用户id缺失")
            customUnAuthText = "登录信息用户id缺失"
            return false
        }
        val homeId = loginInfo.homeId
        if (homeId == null) { //            log.debug("登录用户未选择家庭组信息")
            customUnAuthText = "登录用户未选择家庭组信息"
            return false
        }

        val homeMembers = homeGroupService.findByUserIdAndHomeId(loginUserId, homeId)
        if (homeMembers.isNullOrEmpty()) { //            log.debug("当前账户不在目标家庭组中")
            customUnAuthText = "当前账户不在目标家庭组中"
            return false
        }
        if (Objects.equals(homeMembers[0].type, HomeConstants.PARENT)) { //            log.debug("家长权限操作")
            return true
        }
        if (ApiRightsConstants.HOME_MEMBER_READ == limit.role || ApiRightsConstants.HOME_MEMBER_WRITE == limit.role || ApiRightsConstants.IN_HOME_RIGHT == limit.role) {
            val rights = apiRequest.userOwnsRights?.indexRoleType(limit.roleType)?.indexRole(limit.role)
                ?.indexUrl(apiRequest.url)?.select()
            if (rights.isNullOrEmpty()) { //                log.debug("不存在的用户权限")
                return false
            }
            val right = rights[0]
            val plist = apiLimitService.getUserRightParam(loginUserId)
            for (paramEntity in plist) {
                if (paramEntity.userRightId == null) {
                    continue
                }
                if (paramEntity.userRightId != right.id) {
                    continue
                }
                val numParam = paramEntity.numberValue ?: continue
                if (homeId == numParam.toLong()) {
                    return true
                }
            }
            return false
        }
        return super.auth(limit, apiRequest)
    }

    override fun unAuthedText(
        request: ApiRequest, noPassRights: ApiLimit
    ): String {
        return super.unAuthedText(
            request, noPassRights
        ) + (customUnAuthText ?: ",当前角色非家庭组家长且无相关权限，无法执行操作");
    }
}
